package com.abc.easyclaim;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import com.abc.bean.Case;
import com.abc.bean.Editor;
import com.abc.bean.Template;
import com.abc.bean.Text;
import com.abc.db.DBManager;
import com.abc.tool.Constants;
import com.abc.tool.StringTool;

import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;

public class TextAddActivity extends Activity implements OnClickListener{
	private static final String TAG = "TextAddActivity";
	private DBManager mgr;
	private Integer caseId;
	private List<Template> templateList = new ArrayList<Template>();
	private ListView templateListView;
	private Integer itemid;
	
	private boolean isEdit;
	private Text text = new Text();
	
	private EditText contentEditText;
	private EditText titleEditText;
	private TextView pageNameTextView;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_text_add);
		mgr = MainApplication.getMgr();
		caseId = MainApplication.getCurrentCaseId();
		Button submitBtn = (Button) findViewById(R.id.text_add_save);
		submitBtn.setOnClickListener(this);
		Button backBtn = (Button) findViewById(R.id.text_add_back);
		backBtn.setOnClickListener(this);
		contentEditText = (EditText) findViewById(R.id.text_add_content);
		titleEditText = (EditText) findViewById(R.id.text_add_title);
		pageNameTextView = (TextView) findViewById(R.id.text_add_page_name);
		//获取模板数据
		refreshTemplateList();
		//动态注册广播
		IntentFilter intentFilter = new IntentFilter();  
	    intentFilter.addAction(Constants.ADD_TEMPLATE_INTENT_REFRESH_TEMPLATE_LIST);  
	    registerReceiver(mRefreshBroadcastReceiver, intentFilter);
	    
	    //判断是否是编辑模式
	    Intent intent=getIntent(); 
	    Integer textId = intent.getIntExtra("textId", 0);
	    isEdit=intent.getBooleanExtra("isEdit", false);
	    if(isEdit){
	    	pageNameTextView.setText("编辑文本");
        	text = mgr.queryText(textId);
        	titleEditText.setText(text.getTitle());
        	contentEditText.setText(text.getContent());
	    }
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.text_add, menu);
		return true;
	}

	@Override
	public void onClick(View v) {
		int id = v.getId();
		if(id==R.id.text_add_save){
			getData();
			//创建广播
			Intent intent = new Intent();  
	        intent.setAction(Constants.INTENT_REFRESH_TEXT_LIST);  
	        sendBroadcast(intent);  
			finish();
		}else if (id == R.id.text_add_back) {
			finish();
		}
	}

	private void getData() {
		text.setCaseId(caseId);
		text.setLastModifyDate(StringTool.date2String(new Date(), null));		
		text.setTitle(titleEditText.getText().toString().trim());
		
		text.setContent(contentEditText.getText().toString().trim());
		if(isEdit){
			mgr.modifyText(text);
		}else{
			mgr.addText(text);
		}

		
	}

	private List<String> getTemplateData(){
		List<String> dataList = new ArrayList<String>();
		for (int i = 0; i < templateList.size(); i++) {
			dataList.add(templateList.get(i).getContent());
		}
		return dataList;
	}
	
	
	//创建上下文菜单时触发此方法
    @Override
 	public void onCreateContextMenu(ContextMenu menu, View v,
 			ContextMenuInfo menuInfo) {
 		// TODO Auto-generated method stub
     	getMenuInflater().inflate(R.menu.template_popup_menu, menu);       //添加菜单布局
 		super.onCreateContextMenu(menu, v, menuInfo);
 	}
    
	//上下文菜单的菜单项被单击时触发该方法
    @Override
	public boolean onContextItemSelected(MenuItem item) {
		int menuItem = item.getItemId();
		if (menuItem == R.id.reedit) {
			Editor editor = new Editor("模板编辑","模板内容","");
			editor.toEditPage(TextAddActivity.this);
		} 
		else if (menuItem == R.id.delete) {
			mgr.deleteTemplate((templateList.get(itemid).getId()));
			Log.e(TAG, "template id="+(Integer)templateList.get(itemid).getId()+" has deleteted!");  
			refreshTemplateList();
		} 
		else if (menuItem == R.id.exit) {
			
		}else if(menuItem == R.id.add) {
			Editor editor = new Editor("添加模板","模板内容","");
			editor.toEditPage(TextAddActivity.this);
		}
		return super.onContextItemSelected(item);
	}
    
    private void refreshTemplateList(){
    	templateList = mgr.queryTemplates();
		templateListView = (ListView) findViewById(R.id.template_list_view);
		templateListView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,getTemplateData()));
		//单击事件
		templateListView.setOnItemClickListener(new OnItemClickListener(){ 
            @Override 
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, 
                    long arg3) { 
                //获得选中项的HashMap对象 
            	contentEditText.setText(templateList.get(arg2).getContent());
                
            } 
		             
		}); 
		
		//长按事件
		registerForContextMenu(templateListView);   //为列表注册上下文菜单
		templateListView.setOnItemLongClickListener(new OnItemLongClickListener() {
			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				// TODO Auto-generated method stub
				System.out.println(arg2);
				itemid = arg2;              //传递第几项被选中
				return false;
			}			
		});	
    }
	
    private BroadcastReceiver mRefreshBroadcastReceiver = new BroadcastReceiver() {  
  	  
	      @Override  
	      public void onReceive(Context context, Intent intent) {  
	          String action = intent.getAction();  
	          if (action.equals(Constants.ADD_TEMPLATE_INTENT_REFRESH_TEMPLATE_LIST))  
	          {  
	        	  String value = intent.getStringExtra("value");
	        	  Template template = new Template();
	        	  template.setContent(value);
	        	  mgr.addTemplate(template);
	        	  refreshTemplateList();  
	          }  
	      }  
	};  
}
